"use client";
import axios from "axios";
import { useAuth, useUser } from "@clerk/nextjs";
import {
  Button,
  Modal,
  ModalContent,
  Spacer,
  useDisclosure,
  ModalHeader,
  ModalBody,
  ModalFooter,
  Textarea,
  Input,
  Chip,
  Divider,
} from "@nextui-org/react";
import { ThemeSwitcher } from "./components/ThemeSwitcher";
import { FileUp, Send } from "lucide-react";
import { useEffect, useState } from "react";
import { CldUploadButton } from "next-cloudinary";
import { ToastContainer, toast } from "react-toastify";

// next-cloudinary使用这个存储上传图片NExt使用
import { Topic } from "@/util/type";
import TicketTopic from "./components/TicketTopic";

import "react-toastify/dist/ReactToastify.css";
export default function Home() {
  const { isOpen, onOpen, onOpenChange } = useDisclosure();
  const [content, setContent] = useState("");
  const [options, setOptions] = useState<string[]>([]);
  const [currentOption, setCurrentOption] = useState("");
  const [images, setImages] = useState<string[]>([]);

  const [topics, setTopics] = useState<Topic[]>([]);

  const { userId } = useAuth();
  const avatar = useUser().user?.imageUrl;
  const fetchTicketTopics = async () => {
    console.log("被调用");

    try {
      const response = await axios.get<{ topics: Topic[] }>(
        `${process.env.API_ADDRESS}/topic`
      );
      console.log("获取到的数据", response);
      setTopics(response.data.topics);
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };
  useEffect(() => {
    fetchTicketTopics();
  }, []); // 仅在组件挂载时执行
  return (
    <div>
      <ToastContainer
        position="top-right"
        autoClose={5000}
        hideProgressBar={false}
        newestOnTop={false}
        closeOnClick
        rtl={false}
        pauseOnFocusLoss
        draggable
        pauseOnHover
        theme="light"
      />
      <header className="w-full h-14">
        <div className="fixed top-4 right-8 flex justify-stretch items-center">
          <Button
            color="success"
            endContent={<Send />}
            onPress={onOpen}
            className="mr-40"
          >
            Release
          </Button>
    
        </div>
      </header>
      <div className="flex items-center justify-center m-4">
        <main className="flex flex-col items-center justify-center w-full border-x-2 sm:w-full md:w-9/12 lg:w-6/12">
          <Divider className="my-4" />
          {topics &&
            topics.map((topic) => {
              return (
                <TicketTopic
                  {...topic}
                  key={topic.id}
                  onDeleteSuccess={fetchTicketTopics}
                />
              );
            })}
        </main>
      </div>

      <Modal isOpen={isOpen} onOpenChange={onOpenChange}>
        <ModalContent>
          {(onClose) => (
            <>
              <ModalHeader className="flex flex-col gap-1">
                发布话题
              </ModalHeader>
              <ModalBody>
                <Textarea
                  label="话题内容"
                  placeholder="写一篇话题吧！"
                  variant="underlined"
                  labelPlacement="outside"
                  value={content}
                  onValueChange={setContent}
                />
                <Spacer x={2} />
                <CldUploadButton
                  uploadPreset="i8xrofhf"
                  onSuccess={(result) => {
                    // @ts-ignore
                    setImages([...images, result.info.url]);
                  }}
                >
                  <button className="bg-secondary-400 hover:bg-secondary-700 text-white font-bold py-2 px-4 rounded-lg">
                    <div className="flex">
                      <FileUp />
                      <span>上传图片</span>
                    </div>
                  </button>
                </CldUploadButton>
                <Spacer x={2} />
                <div className="flex items-center">
                  <Input
                    labelPlacement={"outside-left"}
                    label={"输入选项"}
                    variant={"faded"}
                    size="sm"
                    value={currentOption}
                    onValueChange={setCurrentOption}
                  />
                  <Spacer y={2} />
                  <Button
                    color="success"
                    onClick={() => {
                      setOptions([...options, currentOption]);
                      setCurrentOption("");
                    }}
                  >
                    添加
                  </Button>
                </div>
                <Spacer x={2} />
                <div className="flex gap-2">
                  {options.map((item, index) => {
                    return (
                      <Chip
                        key={index}
                        onClose={(e) => {
                          setOptions(options.filter((i) => i !== item));
                        }}
                        variant="flat"
                      >
                        {item}
                      </Chip>
                    );
                  })}
                </div>
              </ModalBody>
              <ModalFooter>
                <Button color="danger" variant="light" onPress={onClose}>
                  取消
                </Button>
                <Button
                  color="primary"
                  onPress={onClose}
                  onClick={async () => {
                    try {
                      const response = await axios.post(
                        process.env.API_ADDRESS + "/topic",
                        {
                          userId: userId,
                          avatar: avatar,
                          content: content,
                          images: images,
                          options: options,
                        },
                        {
                          headers: {
                            "Content-Type": "application/json",
                          },
                        }
                      );
                      console.log("改为axios的响应", response);

                      if (response.status === 200) {
                        toast.success("🦄 发布成功");
                      }

                      const data = response.data;
                      setTopics([...topics, data]);
                      setContent("");
                      setOptions([]);
                      setCurrentOption("");
                      setImages([]);
                    } catch (error) {
                      console.error("Error during API call:", error);
                      toast.error("🦄 网络异常，发布失败");
                      // 您可以添加额外的错误处理逻辑，例如显示一个错误消息给用户
                    }
                  }}
                >
                  确定
                </Button>
              </ModalFooter>
            </>
          )}
        </ModalContent>
      </Modal>
    </div>
  );
}
